package com.zj.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

public class AgeHandler extends BaseTypeHandler<Integer> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer integer, JdbcType jdbcType) throws SQLException {

    }
//注意getDate是根据jdbcType来的，Integer是根据javaType来的
    @Override
    public Integer getNullableResult(ResultSet resultSet, String s) throws SQLException {
        java.sql.Date sqlDate = resultSet.getDate(s);
        return getAge(sqlDate);
    }

    @Override
    public Integer getNullableResult(ResultSet resultSet, int i) throws SQLException {
        java.sql.Date sqlDate = resultSet.getDate(i);
        return getAge(sqlDate);
    }

    @Override
    public Integer getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }


    //由出生日期获得年龄
    public static  Integer getAge(Date birthDay)  {
        if(birthDay==null) return null;
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            System.out.println("The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH)+1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH)+1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }

}
